<?php

namespace Cours\QuizzBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Cours\QuizzBundle\Entity\Quizz;
use Cours\QuizzBundle\Entity\Question;
use Cours\QuizzBundle\Entity\Promotion;
use Cours\QuizzBundle\Entity\Choix;
use \Datetime;

class QuizzController extends Controller {

    public function indexAction()
    {
        return $this->render('CoursQuizzBundle:Quizz:index.html.twig');
    }

    public function createAction()
    {
        $rep = $this->getDoctrine()->getManager()->getRepository('CoursQuizzBundle:Promotion');
        $lesPromo = $rep->findAll();

        foreach ($lesPromo as $p)
        {
            $lesPromos[$p->getId()] = $p->getLibelle();
        }


        $formBuilder = $this->createFormBuilder()
                ->add('titre', 'text')
                ->add('description', 'text')
                ->add('decrementation', 'number',array('label'=>'Valeur retirée par réponses fausse'))
                ->add('active', 'checkbox',array("required"=>false))
                ->add('promotion_id', 'choice', array('choices' => $lesPromos,"label"=>"Promotion"));

        $form = $formBuilder->getForm();
        $request = $this->get('request');

        if ($request->getMethod() == 'POST')
        {
            $form->bind($request);

            if ($form->isValid())
            {
                $unQuizz = new Quizz();
                $unePromo = new Promotion();

                $unePromo = $rep->find($form['promotion_id']->getData());

                $unQuizz->setDateCreation(new DateTime());
                $unQuizz->setTitre($form['titre']->getData());
                $unQuizz->setDescription($form['description']->getData());
                $unQuizz->setActive($form['active']->getData());
                $unQuizz->setDecrementation($form['decrementation']->getData());
                $unQuizz->setPromotion($unePromo);
                $em = $this->getDoctrine()->getManager();
                $em->persist($unQuizz);
                $em->flush();
            }
            return $this->redirect($this->generateUrl('readAllQuizz'));
        }
        return $this->render('CoursQuizzBundle:Quizz:create.html.twig', array('form' => $form->CreateView()));
    }

    public function readAllAction($error=null)
    {

        $this->getDoctrine()->getManager()->getRepository('CoursQuizzBundle:Quizz');

        $rep = $this->getDoctrine()->getManager()->getRepository('CoursQuizzBundle:Quizz');
        $lesQuizz = $rep->findAll();
        if($error==null){
            $a=array('quizz' => $lesQuizz);
        }else{
            $a=array('quizz' => $lesQuizz,"error"=>$error);
        }
        return $this->render('CoursQuizzBundle:Quizz:readAll.html.twig', $a);

    }

    public function updateAction($id)
    {
       if (isset($id) && !empty($id))
        {
            $rep = $this->getDoctrine()->getManager()->getRepository('CoursQuizzBundle:Promotion');
            $lesPromo = $rep->findAll();

            foreach ($lesPromo as $p)
            {
                $lesPromos[$p->getId()] = $p->getLibelle();
            }

            $rep2 = $this->getDoctrine()->getManager()->getRepository('CoursQuizzBundle:Quizz');
            $leQuizz = $rep2->findById($id)[0];

        $formBuilder = $this->createFormBuilder()
                ->add('titre', 'text',array("data"=> $leQuizz->getTitre()))
                ->add('description', 'text',array("data"=> $leQuizz->getDescription()))
                ->add('decrementation', 'number',array('label'=>'Valeur retirée par réponses fausse',"data"=> $leQuizz->getDecrementation()))
                ->add('active', 'checkbox',array("required"=>false,"data"=> $leQuizz->getActive()))
                ->add('promotion_id', 'choice', array('choices' => $lesPromos,"label"=>"Promotion"));

            $form = $formBuilder->getForm();
            $request = $this->get('request');

            if ($request->getMethod() == 'POST')
            {
                $form->bind($request);

                if ($form->isValid())
                {
                    $unePromo = new Promotion();
                    $unePromo = $rep->find($form['promotion_id']->getData());

                    $leQuizz->setDateCreation(new DateTime());
                    $leQuizz->setTitre($form['titre']->getData());
                    $leQuizz->setDescription($form['description']->getData());
                    $leQuizz->setActive($form['active']->getData());
                    $leQuizz->setDecrementation($form['decrementation']->getData());
                    $leQuizz->setPromotion($unePromo);
                    $em = $this->getDoctrine()->getManager();

                    $em->flush();
                }
                return $this->redirect($this->generateUrl('readAllQuizz'));
            }
            return $this->render('CoursQuizzBundle:Quizz:update.html.twig', array('form' => $form->CreateView(),'id'=>$id));
        }
        else
        {
                return $this->redirect($this->generateUrl('readAllQuizz'));
        }
    }

    public function deleteAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $quizz = $em->getRepository('CoursQuizzBundle:Quizz')->find($id);
        if(isset($quizz) && !empty($quizz)){
            $em->remove($quizz);
            $em->flush();
            return $this->redirect($this->generateUrl('readAllQuizz'));
        }
        return $this->redirect($this->generateUrl('readAllQuizz2',array("error"=>"Quizz non trouvé")));
    }


    /* Partie Questions */
    public function readqAction($id=0){
        if(isset($id) && $id>0){
            $em = $this->getDoctrine()->getManager();
            $quizz = $em->getRepository('CoursQuizzBundle:Quizz')->find($id);
            $question = $em->getRepository('CoursQuizzBundle:Question')->findByIdquizz($quizz);

            $c=$em->getRepository('CoursQuizzBundle:Choix');
            $tabChoix=array();
            foreach ($question as $q) {
                $v =$c->findByQuestionId($q->getId());
                if(isset($v) && !empty($v)){
                    $tabChoix[$q->getId()]=$v;    
                }
                unset($v);
            }

            $a=array('quizz' => $quizz,'question'=>$question,"choix"=>$tabChoix);

            return $this->render('CoursQuizzBundle:Questions:readAll.html.twig', $a);
        } else {
            return $this->redirect($this->generateUrl('readAllQuizz2',array("error"=>"Quizz non trouvé")));
        }
    } 

    public function createqAction($id=0){
        if(isset($id) && $id>0){
            $em = $this->getDoctrine()->getManager();
            $quizz = $em->getRepository('CoursQuizzBundle:Quizz')->find($id);
            
            $question = $em->getRepository('CoursQuizzBundle:Question')->findByIdquizz($quizz);

            $qb = $em->createQueryBuilder();
            $qb->select('count(a.id)');
            $qb->from('CoursQuizzBundle:Question','a');

            $count = $qb->getQuery()->getSingleScalarResult();

             $formBuilder = $this->createFormBuilder()
                            ->add('Question', 'text')
                            ->add('decrementation', 'number',array("data"=>"2",'label'=>'Valeur retirée par réponses fausse (0 pour Défault)'));

                    $form = $formBuilder->getForm();
                    $request = $this->get('request');

                    if ($request->getMethod() == 'POST')
                    {
                        $form->bind($request);

                        if ($form->isValid())
                        {
                            $q = new Question();

                            $q->setIdquizz($quizz);
                            $q->setQuestion($form["Question"]->getData());
                            $q->setDecrementation($form['decrementation']->getData());
                            
                            $em = $this->getDoctrine()->getManager();
                            $em->persist($q);
                            $em->flush();
                        }
                        return $this->redirect($this->generateUrl('readQuestion',array("id"=>$quizz->getId())));
                    } 
          return $this->render('CoursQuizzBundle:Questions:create.html.twig', array('form' => $form->CreateView()));
        } else {
            return $this->redirect($this->generateUrl('readAllQuizz2',array("error"=>"Quizz non trouvé")));
        }
    }

        public function updateqAction($idQuestion=0){
        if(isset($idQuestion) && $idQuestion>0){
            $em = $this->getDoctrine()->getManager();
            $q = $em->getRepository('CoursQuizzBundle:Question')->findById($idQuestion)[0];

             $formBuilder = $this->createFormBuilder()
                            ->add('Question', 'text',array('data'=>$q->getQuestion()))
                            ->add('decrementation', 'number',array("data"=>$q->getDecrementation(),'label'=>'Valeur retirée par réponses fausse (0 pour Défault)'));

                    $form = $formBuilder->getForm();
                    $request = $this->get('request');

                    if ($request->getMethod() == 'POST')
                    {
                        $form->bind($request);

                        if ($form->isValid())
                        {
                            $q->setQuestion($form["Question"]->getData());
                            $q->setDecrementation($form['decrementation']->getData());
                            
                            $em = $this->getDoctrine()->getManager();
                            $em->persist($q);
                            $em->flush();
                        }
                        return $this->redirect($this->generateUrl('readQuestion',array("id"=>$q->getIdquizz()->getId())));
                    } 
          return $this->render('CoursQuizzBundle:Questions:create.html.twig', array('form' => $form->CreateView()));
        } else {
            return $this->redirect($this->generateUrl('readAllQuizz2',array("error"=>"Quizz non trouvé")));
        }
    }
    public function deleteqAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $quizz = $em->getRepository('CoursQuizzBundle:Question')->find($id);
        if(isset($quizz) && !empty($quizz)){
            $em->remove($quizz);
            $em->flush();
            return $this->redirect($this->generateUrl('readQuestion',array("id"=>$quizz->getIdquizz()->getId())));
        }
        return $this->redirect($this->generateUrl('readAllQuizz2',array("error"=>"Question non trouvé")));
    }

    public function createcAction(){
        if(isset($_POST) && !empty($_POST)){
            extract($_POST);
            if(isset($id) && isset($libelle) && isset($points)){
                $em = $this->getDoctrine()->getManager();
                $quizz=$em->getRepository('CoursQuizzBundle:Question')->findById($id)[0];
                if(isset($quizz) && !empty($quizz)){
                    $c = new Choix();
                    $c->setPoints($points);
                    $c->setLibelle($libelle);
                    $c->setQuestionId($quizz);

                    $em->persist($c);
                    $em->flush();
                    $tab["id"]=$c->getId();
                    return $this->render('CoursQuizzBundle:Questions:blank.html.twig',array("data" =>$c->getId()));
                }else {
                    $error="Erreur, Aucune Question Associé";
                }
            }else {
                $error="Erreur, Données Incomplètes";
            }   
        } else {
            $error = "Erreur, Aucunes données envoyées";
        }
        return $this->render('CoursQuizzBundle:Questions:blank.html.twig', array("data" =>$error));
    }
    public function updatecAction(){
        if(isset($_POST) && !empty($_POST)){
            extract($_POST);
            if(isset($id)){
                $em = $this->getDoctrine()->getManager();
                $c=$em->getRepository('CoursQuizzBundle:Choix')->findById($id)[0];
                if(isset($c) && !empty($c)){
                    $c->setPoints($points);
                    $c->setLibelle($libelle);

                    $em->persist($c);
                    $em->flush();
                    return $this->render('CoursQuizzBundle:Questions:blank.html.twig',array("data" =>'ok'));
                }else {
                    $error="Erreur, Aucune Question Associé";
                }
            }else {
                $error="Erreur, Données Incomplètes";
            }   
        } else {
            $error = "Erreur, Aucunes données envoyées";
        }
        return $this->render('CoursQuizzBundle:Questions:blank.html.twig', array("data" =>$error));
    }
    public function deletecAction(){
        if(isset($_POST) && !empty($_POST)){
            extract($_POST);
            if(isset($id)){
                $em = $this->getDoctrine()->getManager();
                $choix = $em->getRepository('CoursQuizzBundle:Choix')->find($id);
                if(isset($choix) && !empty($choix)){
                    $em->remove($choix);
                    $em->flush();
                    return $this->render('CoursQuizzBundle:Questions:blank.html.twig',array("data" =>'ok'));
                }
            }
        }
        return $this->render('CoursQuizzBundle:Questions:blank.html.twig', array("data" =>"Erreur"));
    }
}